/*
 * @lc app=leetcode id=257 lang=cpp
 *
 * [257] Binary Tree Paths
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result;
        if (!root) {
            return result;
        }
        deque<TreeNode *> dq;
        dq.push_back(root);
        dfs(root, dq, result);
        return result;
    }

    string buildPath(deque<TreeNode *>& dq) {
        string s;
        stringstream ss; 
        ss << dq[0]->val;
        for (int i=1; i<dq.size(); i++) {
            ss << "->";
            ss << dq[i]->val;
        }
        ss >> s;
        return s;
    }

    void dfs(TreeNode *node, deque<TreeNode *>& dq, vector<string>& result) {

        if (!node->left && !node->right) {
            result.push_back(buildPath(dq));
            return;
        }

        if (node->left) {
            dq.push_back(node->left);
            dfs(node->left, dq, result);
            dq.pop_back();
        } 

        if (node->right) {
            dq.push_back(node->right);
            dfs(node->right, dq, result);
            dq.pop_back();
        }
    }
};

